package com.bhs.sansong.view;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

public class ExpandView extends LinearLayout implements Animator.AnimatorListener {
    private ValueAnimator mShowAction;
    private ValueAnimator mHideAction;
    public boolean isShow = true;

    public ExpandView(Context context) {
        super(context);
    }

    public ExpandView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    private static final int DURATION = 500;// 动画持续时间
    private int measuredHeight;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        measuredHeight = h;
        mHideAction = ValueAnimator.ofInt(h, 0);
        mHideAction.addListener(this);
    }


    @Override
    public void onAnimationStart(Animator animator) {
        if (isShow) {
            setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onAnimationEnd(Animator animator) {
        setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onAnimationCancel(Animator animator) {

    }

    @Override
    public void onAnimationRepeat(Animator animator) {

    }

    public void expand() {
        if (!isShow) {
            mShowAction.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    getLayoutParams().height = (int) animation.getAnimatedValue();
                    requestLayout();
                }
            });

            isShow = true;
            mShowAction.setDuration(DURATION);
            mShowAction.start();
        } else {
            mHideAction.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    getLayoutParams().height = (int) animation.getAnimatedValue();
                    requestLayout();
                }
            });
            if (mShowAction == null) {
                mShowAction = ValueAnimator.ofInt(0, measuredHeight);
                mShowAction.addListener(this);
            }
            isShow = false;
            mHideAction.setDuration(DURATION);
            mHideAction.start();
        }
    }
}
